/**
 * 并发执行任务
 * @param {[()=>Promise<void>]} tasks
 * @param {Number} parallelCount
 */
function paralleTask(tasks, parallelCount = 2) {
  return new Promise(resolve => {
    if (tasks.length === 0) {
      // 传入的任务为空
      resolve();
      return;
    }

    let nextIndex = 0; // 下一个任务的索引
    let finishedCount = 0; // 已完成的任务数量
    /**
     * 执行函数
     */
    function _run() {
      // 运行下一个任务
      const task = tasks[nextIndex];
      nextIndex++;
      task().then(() => {
        finishedCount++;
        if (nextIndex < tasks.length) {
          // 运行下一个任务
          _run();
        } else if (finishedCount === tasks.length) {
          // 任务完成
          resolve();
        }
      });
    }

    for (let i = 0; i < parallelCount && i < tasks.length; i++) {
      // 并发数量执行
      _run();
    }
  });
}

// 测试
function request(url, time = 1) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(`${url} 成功`);
    }, time * 1e3);
  });
}

const requestList = [() => request("http1"), () => request("http2"), () => request("http3"), () => request("http4")];
paralleTask(requestList, 2).then(() => {
  console.log("完成");
});
